import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import 'app_themes.dart';

/// 主题管理器
/// 负责管理应用主题配置
class ThemeManager {
  // 单例实例
  static final ThemeManager _instance = ThemeManager._internal();
  factory ThemeManager() => _instance;
  ThemeManager._internal();
  
  // 单例访问器
  static ThemeManager get to => _instance;
  
  final _storage = GetStorage();
  final _themeKey = 'theme_mode';
  
  // 当前主题模式
  ThemeMode _themeMode = ThemeMode.system;
  ThemeMode get themeMode => _themeMode;
  
  // 当前主题
  ThemeData get theme {
    if (_themeMode == ThemeMode.dark) {
      return AppThemes.darkTheme;
    } else if (_themeMode == ThemeMode.light) {
      return AppThemes.lightTheme;
    } else {
      // 根据系统设置
      final brightness = Get.mediaQuery.platformBrightness;
      return brightness == Brightness.dark 
          ? AppThemes.darkTheme 
          : AppThemes.lightTheme;
    }
  }
  
  @override
  void onInit() {
    super.onInit();
    _loadThemeMode();
  }
  
  // 从存储中加载主题模式
  void _loadThemeMode() {
    final savedThemeMode = _storage.read<String>(_themeKey);
    if (savedThemeMode != null) {
      _themeMode = _getThemeModeFromString(savedThemeMode);
    }
  }
  
  // 字符串转换为主题模式
  ThemeMode _getThemeModeFromString(String themeMode) {
    switch (themeMode) {
      case 'light':
        return ThemeMode.light;
      case 'dark':
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
  
  // 字符串形式的主题模式
  String _getStringFromThemeMode(ThemeMode themeMode) {
    switch (themeMode) {
      case ThemeMode.light:
        return 'light';
      case ThemeMode.dark:
        return 'dark';
      default:
        return 'system';
    }
  }
  
  /// 更新主题模式
  void updateThemeMode(ThemeMode mode) {
    _themeMode = mode;
    Get.changeThemeMode(mode);
    _saveThemeMode(mode);
  }
  
  /// 切换明暗主题
  void toggleTheme() {
    if (_themeMode == ThemeMode.dark) {
      updateThemeMode(ThemeMode.light);
    } else {
      updateThemeMode(ThemeMode.dark);
    }
  }
  
  /// 使用亮色主题
  void useLightTheme() {
    updateThemeMode(ThemeMode.light);
  }
  
  /// 使用暗色主题
  void useDarkTheme() {
    updateThemeMode(ThemeMode.dark);
  }
  
  /// 使用系统主题
  void useSystemTheme() {
    updateThemeMode(ThemeMode.system);
  }
  
  // 保存主题模式到存储
  void _saveThemeMode(ThemeMode themeMode) {
    final themeModeString = _getStringFromThemeMode(themeMode);
    _storage.write(_themeKey, themeModeString);
  }
} 